// sessionStorage
export const session = function (key: string, value: string) {
  if (value === void 0) {
    var lsVal = sessionStorage.getItem(key);
    if (lsVal && lsVal.indexOf('autostringify-') === 0) {
      return JSON.parse(lsVal.split('autostringify-')[1]);
    } else {
      return lsVal;
    }
  } else {
    if (typeof (value) === 'object' || Array.isArray(value)) {
      value = 'autostringify-' + JSON.stringify(value);
    };
    return sessionStorage.setItem(key, value);
  }
}

// 生成随机数
export const getUUID = function (len: any) {
  len = len || 6;
  len = parseInt(len, 10);
  len = isNaN(len) ? 6 : len;
  var seed = '0123456789abcdefghijklmnopqrstubwxyzABCEDFGHIJKLMNOPQRSTUVWXYZ';
  var seedLen = seed.length - 1;
  var uuid = '';
  while (len--) {
    uuid += seed[Math.round(Math.random() * seedLen)];
  }
  return uuid;
};
// 深拷贝
export const deepcopy = function (source: any) {
  if (!source) {
    return source;
  }
  let sourceCopy: any = source instanceof Array ? [] : {};
  for (let item in source) {
    sourceCopy[item] = typeof source[item] === 'object' ? deepcopy(source[item]) : source[item];
  }
  return sourceCopy;
};
// 菜单数据组织
// export const buildMenu = function (array: Array<any>, ckey = 'parentId') {
//   let menuData: Array<any> = [];
//   let indexKeys = Array.isArray(array) ? array.map((e) => {
//     return e.id
//   }) : [];
//   // ckey = ckey || 'parentId';
//   array.forEach(function (e, i) {
//     // 一级菜单
//     if (!e[ckey] || (e[ckey] === e.id)) {
//       delete e[ckey];
//       menuData.push(deepcopy(e)); // 深拷贝
//     } else if (Array.isArray(indexKeys)) {
//       // 检测ckey有效性
//       let parentIndex = indexKeys.findIndex(function (id) {
//         return id === e[ckey];
//       });
//       if (parentIndex === -1) {
//         menuData.push(e);
//       }
//     }
//   });
//   let findChildren = function (parentArr: Array<any>) {
//     if (Array.isArray(parentArr) && parentArr.length) {
//       parentArr.forEach(function (parentNode) {
//         array.forEach(function (node) {
//           if (parentNode.id === node[ckey]) {
//             if (parentNode.children) {
//               parentNode.children.push(node);
//             } else {
//               parentNode.children = [node];
//             }
//           }
//         });
//         if (parentNode.children) {
//           findChildren(parentNode.children);
//         }
//       });
//     }
//   };
//   findChildren(menuData);
//   return menuData;
// }
// 日期格式化
export const dateFormat = function (source: any, ignoreMinute: boolean) {
  var myDate;
  var separate = '-';
  var minute = '';
  if (source === void 0) {
    source = new Date();
  }
  if (source) {
    if (source.split) {
      source = source.replace(/-/g, '/');
    } else if (isNaN(parseInt(source))) {
      source = source.toString().replace(/-/g, '/');
    } else {
      source = new Date(source);
    }

    if (new Date(source) && (new Date(source)).getDate) {
      myDate = new Date(source);
      if (!ignoreMinute) {
        minute = (myDate.getHours() < 10 ? ' 0' : ' ') + myDate.getHours() + ':' + (myDate.getMinutes() < 10 ? '0' : '') + myDate.getMinutes();
      }
      return myDate.getFullYear() + separate + (myDate.getMonth() + 1) + separate + (myDate.getDate() < 10 ? '0' : '') + myDate.getDate() + minute;
    } else {
      return source.slice(0, 16);
    }
  } else {
    return source
  }
};
// ajax错误处理
export const catchError = function (error: any) {
  if (error.response) {
    switch (error.response.status) {
      case 400:
        break;
      case 401:
        sessionStorage.removeItem('user');
        break;
      case 403:
        break;
    }
  }
  return Promise.reject(error);
}

// 日期处理
export const getTime = function (ms: any) {
  if (!ms) return '无'
  if (navigator.appVersion.match(/iphone/ig)) {
    let md = ms.split('.')[0].split('T');
    return md[0] + ' ' + md[1]
  }
  let d = new Date(ms);
  let h: any = d.getHours();
  let m: any = d.getMinutes();
  let s: any = d.getSeconds();
  h = h > 9 ? h : `0${h}`;
  m = m > 9 ? m : `0${m}`;
  s = s > 9 ? s : `0${s}`;
  return `${d.getFullYear()}-${d.getMonth() + 1}-${d.getDate()} ${h}:${m}:${s}`
}

// 日期处理
export const getToday = function () {
  let day = new Date();
  let y: any = day.getFullYear();
  let m: any = day.getMonth() + 1;
  let d: any = day.getDate();
  m = m > 9 ? m : `0${m}`;
  d = d > 9 ? d : `0${d}`;
  return `${y}-${m}-${d}`
}

const pallet = ['red', 'orange', 'yellow darken-1', 'green', 'cyan lighten-2', 'light-blue', 'indigo', 'purple']

// 添加排行着色
export const addRankIndex = function (list: Array<any>, count: number) {
  list.forEach(function (item, i) {
    if (i < count) {
      item.color = pallet[i];
    } else {
      item.color = 'cyan darken-2';
    }
  })

  return list;
}

export const buildMenu = (menu: Array<any>, route: Array<any>): Array<any> => {
  let newMenuMap: any = {};
  route.forEach((item) => {
    let parent = item.meta.parent;
    if (!item.meta.hidden) {
      let menuItem = {
        path: item.menuPath,
        icon: item.meta.icon,
        name: item.menuName,
      };
      if (!newMenuMap[parent]) {
        newMenuMap[parent] = [];
      }
      newMenuMap[parent].push(menuItem)
    }
  });
  menu.forEach((item) => {
    let id = item.id;
    item.children = newMenuMap[id];
  });
  return menu;
}

export const buildMenuConsole = (menu: Array<any>, route: Array<any>): Array<any> => {
  let newMenuMap: any = {};
  route.forEach((item) => {
    let parent = item.meta.parent;
    if (!item.meta.hidden) {
      let menuItem = {
        id: item.id,
        menuId: item.menuId,
        path: item.menuPath,
        icon: item.meta.icon,
        name: item.menuName,
      };
      if (!newMenuMap[parent]) {
        newMenuMap[parent] = [];
      }
      newMenuMap[parent].push(menuItem)
    }
  });
  menu.forEach((item) => {
    let id = item.id;
    item.children = newMenuMap[id];
  });
  return menu;
}

export const buildMenuNoMenu = (menu: Array<any>, route: Array<any>): Array<any> => {
  let newMenuMap: any = {};
  route.forEach((item) => {
    let parent = item.meta.parent;
    if (!item.meta.hidden) {
      let menuItem = {
        id: item.id,
        path: item.path,
        icon: item.meta.icon,
        name: item.name,
      };
      if (!newMenuMap[parent]) {
        newMenuMap[parent] = [];
      }
      newMenuMap[parent].push(menuItem)
    }
  });
  menu.forEach((item) => {
    let id = item.id;
    item.children = newMenuMap[id];
  });
  return menu;
}

export const buildMenuSeller = (route: Array<any>): Array<any> => {
  let menu: Array<any> = [];
  route.forEach((item) => {
    if (!item.meta.hidden) {
      let menuItem = {
        id: item.id,
        menuId: item.menuId,
        path: item.menuPath,
        icon: item.meta.icon,
        name: item.menuName,
      };
      menu.push(menuItem)
    }
  });

  return menu;
}